package com.zhangfb95.crosschain.plugin.client.java.fabric2.infra.config.configuration;

import com.zhangfb95.crosschain.infra.util.tls.client.ReactorNettyWebClientBuilder;
import com.zhangfb95.crosschain.infra.util.tls.client.WebClientSslProperties;
import com.zhangfb95.crosschain.plugin.client.java.fabric2.infra.config.properties.JavaFabric2PluginProperties;
import com.zhangfb95.crosschain.plugin.client.java.fabric2.infra.data.api.container.ChainApi;
import com.zhangfb95.crosschain.plugin.client.java.fabric2.service.impl.JavaFabric2PluginServiceImpl;
import com.zhangfb95.crosschain.protocol.routerpluginapi.PluginServiceRegistry;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

/**
 * @author zhangfubing
 * @since 2023/12/4
 */
@Configuration
public class JavaFabric2PluginConfiguration {

    @Autowired
    private PluginServiceRegistry pluginServiceRegistry;
    @Autowired
    private JavaFabric2PluginProperties javaFabric2PluginProperties;

    @PostConstruct
    public void init() {
        if (CollectionUtils.isEmpty(javaFabric2PluginProperties.getContainerInfos())) {
            return;
        }

        javaFabric2PluginProperties.getContainerInfos().forEach(containerInfo -> {
            WebClientSslProperties sslProperties = new WebClientSslProperties()
                    .setServerUrl(containerInfo.getUrl())
                    .setSslType(containerInfo.getSslType())
                    .setCaCert(containerInfo.getCaCert())
                    .setSslKey(containerInfo.getSslKey())
                    .setSslCert(containerInfo.getSslCert());
            WebClient webClient = ReactorNettyWebClientBuilder.build(sslProperties);
            HttpServiceProxyFactory httpServiceProxyFactory = HttpServiceProxyFactory
                    .builder(WebClientAdapter.forClient(webClient))
                    .build();
            ChainApi chainApi = httpServiceProxyFactory.createClient(ChainApi.class);
            pluginServiceRegistry.register(new JavaFabric2PluginServiceImpl(containerInfo.isEnable(), chainApi));
        });
    }
}
